package com.chen.hello.controller;

import com.chen.hello.model.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {

    @RequestMapping(value = "/getUser",method = RequestMethod.GET)
    public User getUser(){
        User user = new User();
        user.setName("小明");
        user.setAge(12);
        user.setPass("123456");

        return user;
    }

    @RequestMapping(value = "/getUserList",method = RequestMethod.GET)
    public List<User> getUserList(){
        List<User> list = new ArrayList<>();

        User user = new User();
        user.setName("小明");
        user.setAge(12);
        user.setPass("123456");

        list.add(user);

        return list;
    }

    @RequestMapping(value = "getUser1",method = RequestMethod.GET)
    public String getUser(User user){
        return "";
    }


    @RequestMapping(value = "get/{name}",method = RequestMethod.GET)
    public String get(@PathVariable String name){
        return "name:"+name;
    }

    @RequestMapping("/saveUser")
    public void saveUser(@Valid User user, BindingResult result){
        System.out.println("user:"+user);
        if (result.hasErrors()){
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error:list){
                System.out.println(error.getCode()+"-"+error.getDefaultMessage());
            }
        }
    }
}
